/**
 * @file ext-gzpai.js
 *
 *
 * @copyright 2010 CloudCanvas, Inc. All rights reserved
 * @copyright 2021 Optimistik SAS, Inc. All rights reserved
 * @license MIT
 *
 */

 const name = 'gzpai'

 const loadExtensionTranslation = async function (svgEditor) {
   let translationModule
   const lang = svgEditor.configObj.pref('lang')
   try {
     translationModule = await import(`./locale/${lang}.js`)
   } catch (_error) {
     console.warn(`Missing translation (${lang}) for ${name} - using 'en'`)
     translationModule = await import('./locale/en.js')
   }
   svgEditor.i18next.addResourceBundle(lang, name, translationModule.default)
 }
 
 export default {
   name,
   async init() {
     const svgEditor = this
     const { svgCanvas } = svgEditor
     const { ChangeElementCommand } = svgCanvas.history
     const addToHistory = (cmd) => { svgCanvas.undoMgr.addCommandToHistory(cmd) }
     const { $id, $click, $qq, $ } = svgCanvas
     let started
     let newFO, gzp_group, lgId
     let butTitle = ["|◁", "◁", "▷", "▷|", "✔"]
     await loadExtensionTranslation(svgEditor)
     const p = {
       showtool: true,
       x: 0,
       y: 0,
       x1: 0,
       y1: 0,
       h: 50,
       w: 110,
       ws: 15,
       hs: 12,
       bw: 5,
       bh: 1,
       row: 0,
       col: 0,
       last_row: 0,
       last_col: 0,
       cssstyle: { "font-size": 12, "font-family": svgCanvas.getCurText('font_family') }
     }
     const createLg = (id) => {
       var tmp = `<svg><defs>
         <symbol del="gzpai_3" id="gzpai_0" viewBox="0 0 150 50" preserveAspectRatio="none">
           <rect fill="#ffffff" height="49" stroke="url(#lgbut)" stroke-width="5" width="149" x="1" y="1"/>
         </symbol>
         <symbol del="gzpai_3" id="gzpai_1" viewBox="0 0 150 50" preserveAspectRatio="none">
             <rect fill="red" height="49" stroke="url(#lgbut)" stroke-width="5" width="149" x="1" y="1"/>
         </symbol>
         <symbol del="gzpai_3" id="gzpai_2" viewBox="0 0 150 50" preserveAspectRatio="none">
             <rect fill="yellow" height="49" stroke="url(#lgbut)" stroke-width="5" width="149" x="1" y="1"/>
         </symbol>
         <symbol del="gzpai_3" id="gzpai_3" viewBox="0 0 150 50" preserveAspectRatio="none">
             <rect fill="#0000ff" height="49" stroke="url(#lgbut)" stroke-width="5" width="149" x="1" y="1"/>
         </symbol>
         <linearGradient id="lgbut" x1="0" x2="0" y1="0" y2="1">
           <stop offset="0" stop-color="#7f7f7f"/>
           <stop offset="0.4" stop-color="#fff"/>
           <stop offset="0.6" stop-color="#fff"/>
           <stop offset="1" stop-color="#7f7f7f"/>
         </linearGradient>
         </svg></defs>`
       var lgs = $(tmp).find("defs>*")
       if (svgCanvas.findDuplicateGradient(lgs[0]) == null) {
       }else{
         
        $(svgCanvas.findDuplicateGradient(lgs[0])).remove()
        $(svgCanvas.findDuplicateGradient(lgs[1])).remove()
        $(svgCanvas.findDuplicateGradient(lgs[2])).remove()
        $(svgCanvas.findDuplicateGradient(lgs[3])).remove()
       }



       svgCanvas.findDefs().append(lgs[0]);
       svgCanvas.findDefs().append(lgs[1]);
       svgCanvas.findDefs().append(lgs[2]);
       svgCanvas.findDefs().append(lgs[3]);
       svgCanvas.findDefs().append(lgs[4]);
     }
 
     const createGzpaiRectAndText = (parent, id, col_index, row_index, p) => {
       var index = "_" + col_index + "_" + row_index
       var g = createG(id + index, "gzpai_g");
       var rect = svgCanvas.addSVGElementsFromJson({
         element: 'use',
         attr: {
           x: p.x,
           y: p.y,
           width: p.w,
           height: p.h,
           class: 'gzpai',
           id: id + index + "_gzpai",
           "xlink:href": `#gzpai_3`,
         }
       })
 
       var text = svgCanvas.addSVGElementsFromJson({
         element: 'foreignObject',
         curStyles: true,
         attr: {
           x: p.x + p.w / 20,
           y: p.y + p.h / 6,
           width: p.w * 9 / 10,
           height: p.h * 5 / 6,
           class: 'gzpai_text',
           id: id + index + "_gzpai_text",
           'fill': "yellow",
           'text-anchor': 'middle',
           'xml:space': 'preserve',
           'stroke': 'none',
           'opacity': 1,
           'color': 'white'
         }
       })
       text.textContent = "这里显示光字描述"
       setAttrs(text, p.cssstyle)
       g.append(rect)
       g.append(text)
       parent.append(g)
     }
 
     const createG = (id, className) => {
       var g = svgCanvas.addSVGElementsFromJson({
         element: 'g',
         attr: {
           class: className,
           id: id
         }
       })
       return g
     }
 
     const createButtonRect = (id, className, p, parent, textVal) => {
      var g = createG(id+"g","g_but_class")
       var rect = svgCanvas.addSVGElementsFromJson({
         element: 'rect',
         curStyles: false,
         attr: {
           x: p.x,
           y: p.y,
           width: 2,
           height: 2,
           class: className,
           id: id,
           'stroke': '#cccccc',
           'stroke-width': 2,
           'fill': `url(#lgbut)`
         }
       })
       var text = svgCanvas.addSVGElementsFromJson({
         element: 'text',
         curStyles: true,
         attr: {
           x: p.x + 130 / 2,
           y: p.y + 20 / 1.5,
           class: 'but_text',
           id: id + "_text",
           'stroke-width': 1,
           'font-size': 22,
           'font-family': svgCanvas.getCurText('font_family'),
           'text-anchor': 'middle',
           'xml:space': 'preserve',
           'white-space': 'normal'
         }
       })
       text.textContent = textVal
       g.append(rect)
       g.append(text)
       parent.append(g)
     }
     const isGecko = navigator.userAgent.includes('Gecko/')
     const setAttrs = (elem, attrs) => {
       if (isGecko) {
         Object.entries(attrs).forEach(([aname, val]) => {
           elem.setAttribute(aname, val)
         })
       } else {
         Object.entries(attrs).forEach(([aname, val]) => {
           const prop = elem[aname]
           if (prop?.constructor === 'SVGLength') {
             prop.baseVal.value = val
           } else {
             elem.setAttribute(aname, val) 
           }
         })
       }
     }
 
 
     const DrawGzpaiRowAndCol = (p) => {
       p.col = Math.round(Math.abs(p.x1 - p.x - p.ws) / (p.w + p.ws))
       var plus = 1
       if (p.showtool == false) {
         plus = 0
       } else {
         plus = 1
       }
       p.row = Math.round(Math.abs(p.y1 - p.y - (p.hs + p.bh) * plus) / (p.h + p.hs))
       if (p.col > 0 && p.row > 0) {
         if (p.col == p.last_col && p.row == p.last_row) {
           return
         }
         $(gzp_group).empty()
 
         for (var r = 0; r < p.row; r++) {
           for (var i = 0; i < p.col; i++) {
             createGzpaiRectAndText(gzp_group, gzp_group.id, i, r, { x: p.x + p.ws * plus + + i * (p.w + p.ws), y: p.y + (p.bh + p.hs) * plus + r * (p.h + p.hs), w: p.w, h: p.h, cssstyle: p.cssstyle });
           }
         }
         p.last_col = p.col
         p.last_row = p.row
       }
     }
 
     const AjustGzpaiButtons = (p) => {
       p.bw = Math.abs(p.x1 - p.x) / 5
       p.bh = 43
       for (var i = 0; i < butTitle.length; i++) {
         var butpos = { x: p.x + i * (p.bw + 2), y: p.y, width: p.bw, height: p.bh }
         setAttrs($id(newFO.id + "_but_" + i), butpos)
         setAttrs($id(newFO.id + "_but_" + i + "_text"), { x: butpos.x + p.bw / 2, y: butpos.y + p.bh / 1.5 ,fill:'#081e48',stroke:"#081e48",opacity:"1"})
       }
     }
 
     return {
       name: svgEditor.i18next.t(`${name}:name`),
       // The callback should be used to load the DOM with the appropriate UI items
       callback() {
         // Add the button and its handler(s)
         // Note: the star extension needs to be loaded before the polygon extension
         const fbtitle = `${name}:title`
         const titleStar = `${name}:buttons.0.title`
         const titlePolygon = `${name}:buttons.1.title`
         const buttonTemplate = `
                <se-button id="tool_gzpai" title="${titlePolygon}" src="gzpai.svg">
                </se-button>
            `
         svgCanvas.insertChildAtIndex($qq('.shaps .itemWrap'), buttonTemplate, 8)
 
         $click($id('tool_gzpai'), () => {
           if (this.leftPanel.updateLeftPanel('tool_gzpai')) {
             svgCanvas.setMode('gzpai')
           }
         })
       },
       mouseDown(opts) {
         if (svgCanvas.getMode() === 'resize') {
           var eles = svgCanvas.getSelectedElements()
           if (eles.length == 1 && eles[0].classList.contains("gzpai_top")) {
             p.x = eles[0].getBBox().x
             p.y = eles[0].getBBox().y
             p.x1 = eles[0].getBBox().x + eles[0].getBBox().width
             p.y1 = eles[0].getBBox().y + eles[0].getBBox().height
             newFO = eles[0]
             gzp_group = $id(newFO.id + "_group")
             started = true
           } else {
             return
           }
         }
         if (svgCanvas.getMode() === 'gzpai') {
           started = true
           //'x', 'y', 'r1', 'r2', 'angle', 'largeArcFlag', 'sweepFlag'
           p.x = opts.start_x
           p.y = opts.start_y
           var svgId = svgCanvas.getNextId()
           newFO = createG(svgId, "ems gzpai_top")
           newFO.setAttribute("doc-type", 'gzpai')
           createLg(svgId)
           for (var i = 0; i < butTitle.length; i++) {
             createButtonRect(svgId + "_but_" + i, "gzpai_but", { x: p.x + 5, y: p.y - 1 }, newFO, butTitle[i])
           }
 
           gzp_group = createG(svgId + "_group", "gzpai_group")
           newFO.append(gzp_group)
 
           return {
             started: true
           }
         }
         return undefined
       },
       mouseMove(opts) {
         if (!started) {
           return undefined
         }
         const zoom = svgCanvas.getZoom()
         let x = opts.mouse_x / zoom
         let y = opts.mouse_y / zoom
         var eles = svgCanvas.getSelectedElements()
         var doResize = false
         if (svgCanvas.getMode() === 'resize') {
           if (eles.length == 1 && eles[0].classList.contains("gzpai_top")) {
             doResize = true
             if (svgCanvas.getCurrentResizeMode().includes('se')) {
               p.x1 = x
               p.y1 = y
             } else if (svgCanvas.getCurrentResizeMode().includes('e')) {
               p.x1 = x
             } else if (svgCanvas.getCurrentResizeMode().includes('s')) {
               p.y1 = y
             }else{
               return
             }
           } else {
             return
           }
         }
         if (svgCanvas.getMode() === 'gzpai') {
           p.x1 = x
           p.y1 = y
         }
         if (svgCanvas.getMode() === 'gzpai' || (svgCanvas.getMode() === 'resize' && doResize)) {
           AjustGzpaiButtons(p)
           DrawGzpaiRowAndCol(p)
           if (svgCanvas.getMode() === 'resize') {
             svgCanvas.selectorManager.requestSelector(eles[0]).resize()
             svgCanvas.call('transition', eles[0])
           }
           return {
             started: true
           }
         }
         return undefined
       },
       mouseUp() {
         if (svgCanvas.getMode() === 'gzpai') {
           const keep = true
           // svgCanvas.addToSelection([newFO], true);
           return {
             keep,
             element: newFO,
             started: false
           }
         }
         return undefined
       },
       reloadSymbol(){
        createLg(1)
       },
       updategzpai(opts) {
         if (opts.mode != 'gzpai') return
 
         var eles = svgCanvas.getSelectedElements()
         var data = opts.data.gzpaiform
         p.cssstyle = data?.fontSetValue?.cssstyle || p.cssstyle
         p.w = data?.width || p.w
         p.h = data?.height || p.h
         p.ws = data?.lineInterval || p.ws
         p.hs = data?.vertalInterval || p.hs
         var { x, y, width, height } = eles[0].getBBox()
 
         p.x = x
         p.y = y
         p.x1 = x + width
         p.y1 = y + height
         p.last_col = 0
 
         if (data.showtools) {
           if (p.showtool == false) {
             p.x = x - p.ws
             p.y = y - p.hs - p.bh
             p.x1 = x + width + p.ws
             p.y1 = y + height
           }
           p.showtool = true
           $(".gzpai_but").removeClass("hide")
           $(".but_text").removeClass("hide")
         } else {
           if (p.showtool == true) {
             p.x = x + p.ws
             p.y = y + p.hs + p.bh
             p.x1 = x + width - p.ws
             p.y1 = y + height
           }
           p.showtool = false
           $(".gzpai_but").addClass("hide")
           $(".but_text").addClass("hide")
         }
         
         newFO = eles[0]
         gzp_group = $id(newFO.id + "_group")
         AjustGzpaiButtons(p)
         DrawGzpaiRowAndCol(p)
         svgCanvas.selectorManager.requestSelector(eles[0]).resize()
         $(eles[0]).attr("state", btoa(unescape(encodeURIComponent(JSON.stringify(data)))))
         $(eles[0]).attr("data", `${data.tableValue}:${data.equipmentLable}:${data.domainID}`)
         svgEditor.layersPanel.populateObjects()
        // addToHistory(new ChangeElementCommand(eles[0],{state:btoa(unescape(encodeURIComponent(JSON.stringify(data)))),data:`${data.tableValue}:${data.equipmentLable}:${data.domainID}`}))
       }
     }
   }
 }
 